import os
import re
from typing import List

def extract_image_ids(urls: List[str]) -> List[str]:
    """从URL列表中提取图片ID"""
    image_ids = []
    print(f"\n开始处理 {len(urls)} 个URL...")
    for i, url in enumerate(urls, 1):
        # 使用正则表达式匹配URL中的ID部分
        match = re.search(r'/([^/]+)!', url)
        if match:
            image_id = match.group(1)
            image_ids.append(image_id)
            print(f"URL {i}: 成功提取ID: {image_id}")
        else:
            print(f"URL {i}: ⚠️ 无法提取ID，URL格式可能不正确: {url}")
    
    print(f"\n总共提取出 {len(image_ids)} 个有效的图片ID")
    return image_ids

def rename_images(urls: str):
    """根据输入的URL列表重命名图片"""
    # 将输入的字符串按行分割成列表
    url_list = [url.strip() for url in urls.split('\n') if url.strip()]
    print(f"输入的URL总数: {len(url_list)}")
    
    # 提取图片ID
    image_ids = extract_image_ids(url_list)
    
    # 获取sortpic目录中的所有文件
    try:
        files = os.listdir('sortpic')
        print(f"\nsortpic目录中的文件数量: {len(files)}")
        if len(files) > 0:
            print("前5个文件示例:")
            for f in files[:5]:
                print(f"- {f}")
        else:
            print("⚠️ sortpic目录是空的！")
    except FileNotFoundError:
        print("❌ 错误：找不到'sortpic'目录")
        return
    except Exception as e:
        print(f"❌ 访问目录时发生错误: {str(e)}")
        return
    
    # 记录重命名的文件数量
    renamed_count = 0
    not_found_count = 0
    
    # 遍历图片ID列表
    print("\n开始重命名过程...")
    for index, image_id in enumerate(image_ids, start=1):
        found = False
        # 在目录中查找匹配的文件
        for filename in files:
            if image_id in filename:
                # 获取文件扩展名
                _, ext = os.path.splitext(filename)
                # 构建新文件名
                new_filename = f"{index}{ext}"
                # 构建完整的文件路径
                old_path = os.path.join('sortpic', filename)
                new_path = os.path.join('sortpic', new_filename)
                
                try:
                    os.rename(old_path, new_path)
                    print(f"✅ 成功：已将 {filename} 重命名为 {new_filename}")
                    renamed_count += 1
                    found = True
                except OSError as e:
                    print(f"❌ 错误：重命名 {filename} 时发生错误: {e}")
                break
        
        if not found:
            print(f"⚠️ 警告：找不到包含ID {image_id} 的文件")
            not_found_count += 1
    
    print(f"\n执行完成统计:")
    print(f"- 成功重命名: {renamed_count} 个文件")
    print(f"- 未找到匹配: {not_found_count} 个文件")
    print(f"- 总计处理: {len(image_ids)} 个ID")

if __name__ == "__main__":
    print("请输入图片URL列表（每行一个URL，输入完成后按Ctrl+D或Ctrl+Z）：")
    urls = """
https://sns-webpic-qc.xhscdn.com/202502142331/2c2be028bc683dc945b15868c5a4c7bb/1040g2sg30t2km39q3u605o9j09f0jg7sd8lb20g!nd_dft_wlteh_webp_3
https://sns-webpic-qc.xhscdn.com/202502142331/a628d5317d3be2554043a99494c792dc/1040g2sg30t2km39q3u5g5o9j09f0jg7sqiurpjg!nd_dft_wlteh_webp_3
https://sns-webpic-qc.xhscdn.com/202502142331/65317ae3857c53aceb87df753da7519b/1040g2sg30t2km39q3u405o9j09f0jg7sjs7me98!nd_dft_wlteh_webp_3
https://sns-webpic-qc.xhscdn.com/202502142331/441ecb0dfc485b82e21bafddd5ff4ef0/1040g2sg30t2km39q3u2g5o9j09f0jg7si5fvo5g!nd_dft_wlteh_webp_3
https://sns-webpic-qc.xhscdn.com/202502142331/de69f4f88f6a036ef4c0bf8dcdd86314/1040g2sg30t2km39q3u6g5o9j09f0jg7s4fj3mfg!nd_dft_wlteh_webp_3
https://sns-webpic-qc.xhscdn.com/202502142331/2be7016ae18542681afb43862ea5ab37/1040g2sg30t2km39q3u3g5o9j09f0jg7s0ia44h8!nd_dft_wlteh_webp_3
https://sns-webpic-qc.xhscdn.com/202502142331/a6ca6ce404853e09b14ff2fc87d5c4e5/1040g2sg30t2km39q3u305o9j09f0jg7s424gn40!nd_dft_wlteh_webp_3
https://sns-webpic-qc.xhscdn.com/202502142331/c237ef8f459916a69a845532a288e7d2/1040g2sg30t2km39q3u205o9j09f0jg7sj4c9ksg!nd_dft_wlteh_webp_3
https://sns-webpic-qc.xhscdn.com/202502142331/2a94cd8e39691db03d7e05552723286e/1040g2sg30t2km39q3u505o9j09f0jg7sgc6o7h0!nd_dft_wlteh_webp_3
https://sns-webpic-qc.xhscdn.com/202502142331/77f14bf61049fbcae1e5f4345e032a0a/1040g2sg30t2km39q3u105o9j09f0jg7sctae7s8!nd_dft_wlteh_webp_3
https://sns-webpic-qc.xhscdn.com/202502142331/f8b532cce62d37765ec2b08605f4eb7f/1040g2sg30t2km39q3u4g5o9j09f0jg7sivdsg0o!nd_dft_wlteh_webp_3"""
    rename_images(urls) 